"""
计算器内存管理模块
提供内存存储、调用、加减和清空功能
"""
from typing import Optional, Callable


class MemoryManager:
    """计算器内存管理器"""
    
    def __init__(self, callback: Optional[Callable[[float], None]] = None):
        """
        初始化内存管理器
        
        Args:
            callback: 内存值变化时的回调函数，用于更新GUI显示
        """
        self._memory_value: float = 0.0
        self._callback = callback
    
    @property
    def value(self) -> float:
        """获取当前内存值"""
        return self._memory_value
    
    def clear(self) -> None:
        """清空内存（MC - Memory Clear）"""
        self._memory_value = 0.0
        self._notify_change()
    
    def recall(self) -> float:
        """调用内存值（MR - Memory Recall）"""
        return self._memory_value
    
    def add(self, value: float) -> None:
        """
        将值添加到内存（M+ - Memory Add）
        
        Args:
            value: 要添加的值
        """
        try:
            self._memory_value += float(value)
            self._notify_change()
        except (ValueError, TypeError):
            raise ValueError("无效的数值")
    
    def subtract(self, value: float) -> None:
        """
        从内存中减去值（M- - Memory Subtract）
        
        Args:
            value: 要减去的值
        """
        try:
            self._memory_value -= float(value)
            self._notify_change()
        except (ValueError, TypeError):
            raise ValueError("无效的数值")
    
    def store(self, value: float) -> None:
        """
        存储值到内存（MS - Memory Store）
        
        Args:
            value: 要存储的值
        """
        try:
            self._memory_value = float(value)
            self._notify_change()
        except (ValueError, TypeError):
            raise ValueError("无效的数值")
    
    def is_empty(self) -> bool:
        """检查内存是否为空"""
        return self._memory_value == 0.0
    
    def set_callback(self, callback: Callable[[float], None]) -> None:
        """
        设置内存值变化的回调函数
        
        Args:
            callback: 回调函数，参数为当前内存值
        """
        self._callback = callback
    
    def _notify_change(self) -> None:
        """通知内存值变化"""
        if self._callback:
            self._callback(self._memory_value)
    
    def get_formatted_value(self, precision: int = 10) -> str:
        """
        获取格式化的内存值字符串
        
        Args:
            precision: 显示精度
            
        Returns:
            格式化的内存值字符串
        """
        if self._memory_value == 0:
            return "0"
        
        # 如果是整数，显示为整数
        if self._memory_value == int(self._memory_value):
            return str(int(self._memory_value))
        
        # 否则显示为浮点数，去除末尾的零
        formatted = f"{self._memory_value:.{precision}f}".rstrip('0').rstrip('.')
        return formatted if formatted else "0"
    
    def __str__(self) -> str:
        """字符串表示"""
        return f"MemoryManager(value={self._memory_value})"
    
    def __repr__(self) -> str:
        """调试字符串表示"""
        return self.__str__()


class MultiMemoryManager:
    """多内存位管理器，支持多个内存位"""
    
    def __init__(self, memory_slots: int = 10, callback: Optional[Callable[[int, float], None]] = None):
        """
        初始化多内存位管理器
        
        Args:
            memory_slots: 内存位数量
            callback: 内存值变化时的回调函数，参数为(slot_index, value)
        """
        self._memory_slots = [0.0] * memory_slots
        self._callback = callback
        self._current_slot = 0
    
    @property
    def current_slot(self) -> int:
        """获取当前内存位"""
        return self._current_slot
    
    @current_slot.setter
    def current_slot(self, slot: int) -> None:
        """设置当前内存位"""
        if 0 <= slot < len(self._memory_slots):
            self._current_slot = slot
        else:
            raise ValueError(f"内存位索引超出范围 (0-{len(self._memory_slots)-1})")
    
    def get_value(self, slot: Optional[int] = None) -> float:
        """
        获取指定内存位的值
        
        Args:
            slot: 内存位索引，如果为None则使用当前内存位
        """
        if slot is None:
            slot = self._current_slot
        
        if 0 <= slot < len(self._memory_slots):
            return self._memory_slots[slot]
        else:
            raise ValueError(f"内存位索引超出范围 (0-{len(self._memory_slots)-1})")
    
    def store(self, value: float, slot: Optional[int] = None) -> None:
        """
        存储值到指定内存位
        
        Args:
            value: 要存储的值
            slot: 内存位索引，如果为None则使用当前内存位
        """
        if slot is None:
            slot = self._current_slot
        
        if 0 <= slot < len(self._memory_slots):
            self._memory_slots[slot] = float(value)
            self._notify_change(slot, self._memory_slots[slot])
        else:
            raise ValueError(f"内存位索引超出范围 (0-{len(self._memory_slots)-1})")
    
    def clear(self, slot: Optional[int] = None) -> None:
        """
        清空指定内存位
        
        Args:
            slot: 内存位索引，如果为None则清空当前内存位
        """
        if slot is None:
            slot = self._current_slot
        
        if 0 <= slot < len(self._memory_slots):
            self._memory_slots[slot] = 0.0
            self._notify_change(slot, 0.0)
        else:
            raise ValueError(f"内存位索引超出范围 (0-{len(self._memory_slots)-1})")
    
    def clear_all(self) -> None:
        """清空所有内存位"""
        for i in range(len(self._memory_slots)):
            self._memory_slots[i] = 0.0
            self._notify_change(i, 0.0)
    
    def get_all_values(self) -> list[float]:
        """获取所有内存位的值"""
        return self._memory_slots.copy()
    
    def set_callback(self, callback: Callable[[int, float], None]) -> None:
        """
        设置内存值变化的回调函数
        
        Args:
            callback: 回调函数，参数为(slot_index, value)
        """
        self._callback = callback
    
    def _notify_change(self, slot: int, value: float) -> None:
        """通知内存值变化"""
        if self._callback:
            self._callback(slot, value)
    
    def __str__(self) -> str:
        """字符串表示"""
        return f"MultiMemoryManager(slots={len(self._memory_slots)}, current={self._current_slot})"